<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Product extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();

        $this->load->model('MStorageProduct');
        $this->_validation = Array(
            array('field' => 'purchaser_id', 'label' => '采购人ID', 'rules' => 'integer|max_length[11]')
        , array('field' => 'product_name', 'label' => '商品名称', 'rules' => 'trim|required|max_length[255]')
        , array('field' => 'price', 'label' => '价格', 'rules' => 'required')
        , array('field' => 'unit', 'label' => '单位', 'rules' => 'required')
        , array('field' => 'product_type', 'label' => '产品类型', 'rules' => 'required')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        );
    }

    public function index()
    {
        $this->load->model('MAdmin');
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');

        $this->formfilter->addFilter('p.id', 'where');
        $this->formfilter->addFilter('p.product_name', 'like');
        $this->formfilter->addFilter('p.purchaser_id', 'where');

        if ($begintime = filterValue('product_create_time_begin')) {
            $this->formfilter->addFilter('product_create_time_begin', 'where', array('p.create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('product_create_time_end')) {
            $this->formfilter->addFilter('product_create_time_end', 'where', array('p.create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('product_number_perpage');
        $order_type = filterValue('product_order_type');

        $total_number = $this->MStorageProduct->getCount();
        $limit = $this->pagination($total_number,'',$number_perpage);
        $list = $this->MStorageProduct->getList($limit,$order_type);
        $allPurchaser = $this->MAdmin->getAllPurchaser();
        $this->assign('list', $list);
        $this->assign('allPurchaser', $allPurchaser);
        $this->layout();
    }

    public function add()
    {
        $obj = $this->MStorageProduct->createVo();
        $obj->purchaser_id = $this->_user->id;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            if ($this->MStorageProduct->add($newObj)) {
                successAndRedirect('添加任务成功');
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('obj', $obj);
        $this->layout();
    }

    function edit($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MStorageProduct->getOne(Array('id' => $id));
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        $this->editObj = $obj;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            if ($this->MStorageProduct->update($newObj)) {
                $content = '';
                foreach ($newObj as $key =>$value){
                    if ($key == 'price'){
                        $newObj->$key = (float)$newObj->$key;
                        $obj->$key = (float)$obj->$key;
                    }
                    if ($newObj->$key !== $obj->$key && $key !== 'update_time'){

                        $content .= ' '.IOSS_StaticConfig::translateLogField($key).' 由 '.$obj->$key.' 改为 '.$newObj->$key.';';
                    }
                }
                if ($content){
                     $this->editLog($this->_user->id,$id,$this->_thisModule.$this->_thisController.'/'.$this->_thisMethod,$content);
                }
                successAndRedirect(l('edit_success'));
            } else {
                $this->db->trans_complete();
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('obj', $obj);
        $this->layout();
    }

    function view($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->load->model('MStorageProduct');
        $obj = $this->MStorageProduct->getOne(Array('id' => $id));
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }

        $this->load->model('MAdmin');
        $this->load->model('MShop');
        $this->load->model('MStorageWarehouse');
        $allPurchaser = $this->MAdmin->getAllPurchaser();
        $allShops = $this->MShop->getAllShopsTrue();

        $total_number = $this->MStorageWarehouse->getWareCount($id);
        $limit = $this->pagination($total_number,'',20);
        $housings = $this->MStorageWarehouse->getWareList($limit,$id);

        $this->assign('obj', $obj);
        $this->assign('allPurchaser', $allPurchaser);
        $this->assign('allShops', $allShops);
        $this->assign('housings', $housings);
        $this->assign('quantity', $this->MStorageWarehouse->getQuantity($id));
        $this->layout('view.tpl');
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MTask->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    function ajaxTaskApply(){
        $this->load->model('MTaskApplyNum');
        $this->load->helper('populate');
        $data = $this->input->post();
        $obj = $this->MTask->getOne(Array('id' => $data['task_id']));
        if (!$obj) {
            exit(json_encode([
                'success' => 0,
                'msg' => '无效的任务'
            ]));
        }
        $this->db->trans_start();
        $his = $this->MTaskApplyNum->getOne([
            'task_id' => $data['task_id'],
            'operator_id' => $this->_user->id
        ]);
        if ($data['apply_type'] == 'sale') {
            $obj->sale_applied_num += $data['apply_num'];
            if ($obj->sale_applied_num > $obj->sale_need_num) {
                exit(json_encode([
                    'success' => 0,
                    'msg' => '超出最大可接销量数目，请刷新后重试'
                ]));
            }
            if ($his) {
                $his->apply_sale_num += $data['apply_num'];
                if (!$this->MTaskApplyNum->update($his)) {
                    $this->db->_trans_status = FALSE;
                }
            } else {
                $add_obj = $this->MTaskApplyNum->createVo();
                $add_obj->apply_sale_num = $data['apply_num'];
                $new_add_obj = populate((Object)((Array)$add_obj), $data);
                if (!$this->MTaskApplyNum->add($new_add_obj)) {
                    $this->db->_trans_status = FALSE;
                }
            }
        } else if ($data['apply_type'] == 'comment') {
            $obj->comment_applied_num += $data['apply_num'];
            if ($obj->comment_applied_num > $obj->comment_need_num) {
                exit(json_encode([
                    'success' => 0,
                    'msg' => '超出最大可接测评数目，请刷新后重试'
                ]));
            }
            if ($his) {
                $his->apply_comment_num += $data['apply_num'];
                if (!$this->MTaskApplyNum->update($his)) {
                    $this->db->_trans_status = FALSE;
                }
            } else {
                $add_obj = $this->MTaskApplyNum->createVo();
                $add_obj->apply_comment_num = $data['apply_num'];
                $new_add_obj = populate((Object)((Array)$add_obj), $data);
                if (!$this->MTaskApplyNum->add($new_add_obj)) {
                    $this->db->_trans_status = FALSE;
                }
            }
        }

        $newObj = populate((Object)((Array)$obj), $data);
        if (!$this->MTask->update($newObj)) {
            $this->db->_trans_status = FALSE;
        }

        $this->db->trans_complete();
        if ($this->db->trans_status() !== FALSE) {
            exit(json_encode([
                'success' => 1,
                'msg' => '操作成功'
            ]));
        } else {
            exit(json_encode([
                'success' => 0,
                'msg' => '操作失败'
            ]));
        }
    }
}
